package com.ruoyi.report.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.DownloadFile;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.qrCode.ZipUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.onlyoffice.domain.OnFile;
import com.ruoyi.onlyoffice.service.IOnFileService;
import com.ruoyi.report.domain.ReportInformation;
import com.ruoyi.report.domain.ReportOrginalimage;
import com.ruoyi.report.domain.ReportOrginalrecord;
import com.ruoyi.report.service.IReportInformationService;
import com.ruoyi.report.service.IReportOrginalimageService;
import com.ruoyi.report.service.IReportOrginalrecordService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报告信息Controller
 * 
 * @author luguanqing
 * @date 2020-11-17
 */
@RestController
@RequestMapping("/report/information")
@Api(value="报告信息管理",tags = "报告信息管理")
public class ReportInformationController extends BaseController
{
    @Autowired
    private IReportInformationService reportInformationService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IReportOrginalimageService reportOrginalimageService;

    @Autowired
    private IReportOrginalrecordService reportOrginalrecordService;

    @Autowired
    private IOnFileService OnFileService;


    /**
     * 查询报告信息列表
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('report:information:list')")
    @ApiOperation(value="查询报告信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "pageNum", value = "页数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "pageSize", value = "每页记录数", required = true, dataType = "String"),
    })
    public TableDataInfo list(ReportInformation reportInformation)
    {
        startPage();
        List<ReportInformation> list = reportInformationService.selectReportInformationList(reportInformation);
        //获取详情
        if(null != list && !list.isEmpty()) {
            for(ReportInformation rt : list) {
                rt.setReportOrginalrecord(reportOrginalrecordService.selectReportOrginalrecordByReportNum(rt.getReportNum()));
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询到期报告信息列表
     */
    @GetMapping("/expirationList")
    @ApiOperation(value="查询到期报告信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "pageNum", value = "页数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "pageSize", value = "每页记录数", required = true, dataType = "String"),
    })
    public TableDataInfo expirationList(ReportInformation reportInformation)
    {
        startPage();
        List<ReportInformation> list = reportInformationService.selectExpirationTime(reportInformation);
        return getDataTable(list);
    }

    /**
     * 导出报告信息列表
     */
    @Log(title = "报告信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportInformation reportInformation)
    {
        List<ReportInformation> list = reportInformationService.selectReportInformationList(reportInformation);
        ExcelUtil<ReportInformation> util = new ExcelUtil<ReportInformation>(ReportInformation.class);
        util.exportExcel(response, list, "报告信息");
    }

    /**
     * 获取报告信息详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取报告信息详细信息")
    @ApiImplicitParam(paramType="query", name = "id", value = "报告id", required = true, dataType = "String")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(reportInformationService.selectReportInformationById(id));
    }

    /**
     * 查询报告数量
     */
    @GetMapping(value = "/getCount/{state}")
    @ApiOperation(value="查询报告数量")
    @ApiImplicitParam(paramType="query", name = "state", value = "状态", required = true, dataType = "String")
    public AjaxResult getCount(@PathVariable("state") String state){
        if(StringUtils.equalsIgnoreCase("undefined", state)){
            state = null;
        }
        int ret = reportInformationService.selectReportInformationCount(state);
        return AjaxResult.success(ret);
    }

    /**
     * 根据日期查询报告数量
     */
    @GetMapping(value = "/getCountByDate/{dateLength}")
    @ApiOperation(value="根据日期查询报告数量")
    @ApiImplicitParam(paramType="query", name = "dateLength", value = "日期", required = true, dataType = "String")
    public AjaxResult getCountByDate(@PathVariable("dateLength") Integer dateLength){
        return AjaxResult.success(reportInformationService.selectReportNumByDate(dateLength));
    }

    /**
     * 根据项目编号获取原始记录图片
     */
    @GetMapping(value = "/getOrginalImageByNum")
    @ApiOperation(value="根据项目编号获取原始记录图片")
    @ApiImplicitParam(paramType="query", name = "reportNum", value = "报告编号", required = true, dataType = "String")
    public AjaxResult getOrginalImageByNum(@RequestParam String reportNum){
        //获取列表信息
        ReportOrginalrecord reportOrginalrecord = reportOrginalrecordService.selectReportOrginalrecordByReportNum(reportNum);
        if(reportOrginalrecord != null) {
            ReportOrginalimage reportOrginalimage = new ReportOrginalimage();
            reportOrginalimage.setoId(reportOrginalrecord.getId());
            List<ReportOrginalimage> list = reportOrginalimageService.selectReportOrginalimageList(reportOrginalimage);
            List<String> profiles = new ArrayList<>();
            //拼接返回图片
            if(list.size() > 0) {
                for(ReportOrginalimage r : list) {
                    profiles.add(r.getProfile());
                }
            }
            return AjaxResult.success(profiles.stream().collect(Collectors.joining(",")));
        }
        return AjaxResult.success();
    }

    /**
     * 报告直接上传
     */
    @Log(title = "报告直接上传", businessType = BusinessType.INSERT)
    @PostMapping("/uploadReport")
    @ApiOperation(value="报告直接上传")
    public AjaxResult uploadReport(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String fileName = FileUploadUtils.upload(RuoYiConfig.getProfile() + RuoYiConfig.getDocumentPath(), file, false);
            String profile =  RuoYiConfig.getProfile();
            AjaxResult ajax = AjaxResult.success();
            if(StringUtils.isNotEmpty(fileName)){
                //上传到onlyoffice服务器
//                FileUtils fileUtils = new FileUtils();
//                fileUtils.copyFile(StringUtils.replace(fileName, "/profile", profile), RuoYiConfig.onlyOffice + StringUtils.substring(fileName, fileName.lastIndexOf("/") + 1, fileName.length()));
                ajax.put("fileName", StringUtils.replace(fileName, profile, "/profile"));
                return ajax;
            }
        }
        return AjaxResult.error("上传文件异常，请联系管理员");
    }

    /**
     * 批量Zip文件下载
     * @param id 文件Id
     */
    @GetMapping("/downloadZip")
    @ApiOperation(value="批量Zip文件下载")
    public void fileDownloadZip(@RequestParam String id, @RequestParam String userName,HttpServletResponse response, HttpServletRequest request) throws IOException {
        //获取报告信息
        ReportInformation reportInformation = reportInformationService.selectReportInformationById(id);
        //获取报告封面和内容
        List<DownloadFile> downloadFiles = new ArrayList<DownloadFile>();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        String fileName = reportInformation.getReportNum();
        String actualEndTime =DateUtils.getTime();
        fileName += "-" + actualEndTime + ".zip";
        response.setHeader("Content-Disposition","attachment; filename="+fileName);
        ZipUtil.toZip3(downloadFiles, response.getOutputStream());
        reportInformation.setDowner(userName);
        reportInformationService.updateReportInformation(reportInformation);
    }

    /**
     * 导入模板下载
     * @return
     */
    @PostMapping("/importTemplate")
    @ApiOperation(value="导入模板下载")
    public void importTemplate(HttpServletResponse response)
    {
        List<ReportInformation> list = reportInformationService.selectReportInformationList(new ReportInformation());
        //转换获取报告第一条数据
        List<ReportInformation> newList = new ArrayList<>();
        newList.add(list.get(0));
        ExcelUtil<ReportInformation> util = new ExcelUtil<ReportInformation>(ReportInformation.class);
        util.exportExcel(response, newList, "报告信息");
    }

    /**
     * 报告信息导入
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    @ApiOperation(value="报告信息导入")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<ReportInformation> util = new ExcelUtil<ReportInformation>(ReportInformation.class);
        List<ReportInformation> reportInfoList = util.importExcel(file.getInputStream());
        String message = reportInformationService.importReport(reportInfoList);
        return AjaxResult.success(message);
    }


    /**
     * 新增报告信息
     */
    @Log(title = "报告信息", businessType = BusinessType.INSERT)
    @ApiOperation(value="新增报告信息")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add( @RequestBody ReportInformation reportInformation) throws IOException {
        String profile = RuoYiConfig.getProfile();
        String id = IdUtils.fastSimpleUUID();
        reportInformation.setId(IdUtils.fastSimpleUUID());
        if(StringUtils.isNotEmpty(reportInformation.getPdfReport())) {
            reportInformation.setState("6");
        }else {
            reportInformation.setState("1");
        }
        reportInformation.setUploader(SecurityUtils.getLoginUser().getUser().getNickName());
        if(StringUtils.isEmpty(reportInformation.getChiefInspector())) {
            reportInformation.setChiefInspector(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        SysUser sysUser = new SysUser();
        sysUser.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        reportInformation.setFileId(id);
        reportInformation.setUploadType("1");
        int ret = reportInformationService.insertReportInformation(reportInformation);
        //上传到onlyoffice服务器
        if(ret > 0 && StringUtils.isNotEmpty(reportInformation.getReportUrl())) {
            //保存成功后添加记录到历史oo列表中
            OnFile onFile = new OnFile();
            onFile.setFileId(id);
            String reportUrl = reportInformation.getReportUrl();
            onFile.setFileName(reportInformation.getReportNum() + StringUtils.substring(reportUrl, reportUrl.indexOf(".")));
            onFile.setFileType(StringUtils.substring(reportUrl, reportUrl.indexOf(".") + 1));
            onFile.setVersion("1.0.0");
            onFile.setCreatedTimes(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            onFile.setUserId(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
            onFile.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
            onFile.setReportId(reportInformation.getId());
            OnFileService.insertOnFile(onFile);
            //将当前文件保存到onlyoffice服务器地址下
            FileUtils fileUtils = new FileUtils();
            fileUtils.copyFile(StringUtils.replace(reportUrl, "/profile", profile), RuoYiConfig.getOoFile() +"\\"+onFile.getFileId()+"."+onFile.getFileType());
        }
        //原始记录上传
        if(ret > 0 && null != reportInformation.getReportOrginalrecord()) {
            ReportOrginalrecord reportOrginalrecord = reportInformation.getReportOrginalrecord();
            reportOrginalrecord.setReportNum(reportInformation.getReportNum());
            reportOrginalrecord.setItemNum(reportInformation.getAgreementNum());
            reportOrginalrecord.setItemType(reportInformation.getReportType());
            reportOrginalrecord.setClient(reportInformation.getClient());
            reportOrginalrecord.setEquType(reportInformation.getSampleType());
            reportOrginalrecord.setUploadTime(DateUtils.getNowDate());
            reportOrginalrecord.setUploader(SecurityUtils.getLoginUser().getUser().getNickName());
            reportOrginalrecordService.insertReportOrginalrecord(reportOrginalrecord);
        }
        return toAjax(ret);
    }

    /**
     * 报告签字
     */
    @PostMapping("/reportSign")
    @ApiOperation(value="报告签字")
    public AjaxResult reportSign(@RequestBody ReportInformation reportInformation){
        //签字确认
        //if(Integer.valueOf(reportInformation.getState()) > 2  && !StringUtils.equals(reportInformation.getState(), "9")  && !StringUtils.equals(reportInformation.getState(), "7") && !StringUtils.equals(reportInformation.getState(), "5")){
        //    String sign;
        //    String newFilePath = RuoYiConfig.sign +  String.valueOf(new SnowflakeIdUtils(0, 0).nextId()) + ".png";
        //    OaNews oaNews = new OaNews();
        //    oaNews.setId(String.valueOf(new SnowflakeIdUtils(0, 0).nextId()));
        //    oaNews.setReceiver(reportInformation.getUploader());
        //    oaNews.setSender("0");
        //    oaNews.setType("1");
        //    oaNews.setStatus("1");
        //    //主检签字
        //    if(StringUtils.isNotEmpty(reportInformation.getChiefReg()) ){
        //        //签字版获取
        //        if(!reportInformation.getChiefReg().contains("profile")){
        //            //签字版签字
        //            sign = reportInformation.getChiefReg();
        //            sign = StringUtils.substring(sign, StringUtils.lastIndexOf(sign, ",") + 1, sign.length());
        //            if(Base64ToImg.generateImg(sign, newFilePath)){
        //                reportInformation.setChiefReg(newFilePath);
        //            }
        //        }
        //        oaNews.setTitle("您的报告编号为：" + reportInformation.getReportNum() + "已被主检");
        //    } else if(StringUtils.isNotEmpty(reportInformation.getExamineReg())){//审核签字
        //        //签字版签字
        //        if(!reportInformation.getExamineReg().contains("profile")){
        //            sign = reportInformation.getExamineReg();
        //            sign = StringUtils.substring(sign, StringUtils.lastIndexOf(sign, ",") + 1, sign.length());
        //            if(Base64ToImg.generateImg(sign, newFilePath)){
        //                reportInformation.setExamineReg(newFilePath);
        //            }
        //        }
        //        oaNews.setTitle("您的报告编号为：" + reportInformation.getReportNum() + "已被审核");
        //    }else if(StringUtils.isNotEmpty(reportInformation.getApprReg())) {//批准签字
        //        //签字版签字
        //        if (!reportInformation.getApprReg().contains("profile")) {
        //            sign = reportInformation.getApprReg();
        //            sign = StringUtils.substring(sign, StringUtils.lastIndexOf(sign, ",") + 1, sign.length());
        //            if (Base64ToImg.generateImg(sign, newFilePath)) {
        //                reportInformation.setApprReg(newFilePath);
        //            }
        //        }
        //        oaNews.setTitle("您的报告编号为：" + reportInformation.getReportNum() + "已被批准");
        //    }
        //    List<OaNews> oaNewsList = new ArrayList<OaNews>(16);
        //    oaNewsList.add(oaNews);
        //    newsService.insertOaNews(oaNewsList);
        //    reportInformationService.reportSimpleSign(reportInformation);
        //}
        //状态变更
        return toAjax(reportInformationService.updateReportStateByNum(reportInformation.getReportNum(), reportInformation.getState()));
    }

    /**
     * 报告委派审批信息
     */
    @PutMapping("/assignReport")
    @ApiOperation(value="报告委派审批信息")
    public AjaxResult assignReport(@RequestBody ReportInformation reportInformation) {
        //获取报告审核人
        if(StringUtils.isNotEmpty(reportInformation.getExamInspector())) {
            SysUser sysUser = new SysUser();
            sysUser.setNickName(reportInformation.getExamInspector());
            reportInformation.setExamStatus("0");
        }
        //获取报告批准人
        if(StringUtils.isNotEmpty(reportInformation.getApprInspector())) {
            SysUser sysUser = new SysUser();
            sysUser.setNickName(reportInformation.getApprInspector());
            reportInformation.setApprStatus("0");
        }
        return toAjax(reportInformationService.updateReportInformation(reportInformation));
    }

    /**
     * 报告委托人审批报告
     */
    @PutMapping("/dealReport")
    @ApiOperation(value="报告委托人审批报告")
    public AjaxResult dealReport(@RequestBody ReportInformation reportInformation) {
        int ret = 0;
        //报告审核
        if(StringUtils.isNotEmpty(reportInformation.getExamInspector()) && Integer.valueOf(reportInformation.getExamStatus()) > 0) {
            ret = reportInformationService.updateReportInformation(reportInformation);
        }
        //报告批准
        if(StringUtils.isNotEmpty(reportInformation.getApprInspector()) && Integer.valueOf(reportInformation.getApprStatus()) > 0) {
            //变更报告原始状态
            if(StringUtils.equals("1", reportInformation.getExamStatus()) && StringUtils.equals("1", reportInformation.getApprStatus())) {
                reportInformation.setState("2");
            }else {
                reportInformation.setState("3");
            }
            ret = reportInformationService.updateReportInformation(reportInformation);
        }
        return toAjax(ret);
    }


    /**
     * 修改报告信息
     */
    @Log(title = "报告信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改报告信息")
    public AjaxResult edit(@RequestBody ReportInformation reportInformation)
    {
        int ret = reportInformationService.updateReportInformation(reportInformation);
        //原始记录上传
        if(ret > 0 && null != reportInformation.getReportOrginalrecord()) {
            //删除原数据
            reportOrginalrecordService.deleteReportOrginalrecordByReportNum(reportInformation.getReportNum());
            ReportOrginalrecord reportOrginalrecord = reportInformation.getReportOrginalrecord();
            reportOrginalrecord.setReportNum(reportInformation.getReportNum());
            reportOrginalrecord.setItemNum(reportInformation.getAgreementNum());
            reportOrginalrecord.setItemType(reportInformation.getReportType());
            reportOrginalrecord.setClient(reportInformation.getClient());
            reportOrginalrecord.setEquType(reportInformation.getSampleType());
            reportOrginalrecord.setUploadTime(DateUtils.getNowDate());
            reportOrginalrecord.setUploader(SecurityUtils.getLoginUser().getUser().getNickName());
            reportOrginalrecordService.insertReportOrginalrecord(reportOrginalrecord);
        }
        return toAjax(ret);
    }


    /**
     * 审批未通过原因
     */
    @GetMapping(value = "/getReason/{id}/{state}")
    @ApiOperation(value="审批未通过原因")
    public AjaxResult selectReasonById(@PathVariable("id") String id, @PathVariable("state") String state){
        return AjaxResult.success(reportInformationService.selectReasonById(id, state));
    }

    /**
     * 首页获取报告审批信息
     */
    @GetMapping(value = "/getReport/count")
    @ApiOperation(value="首页获取报告审批信息")
    public AjaxResult getReportCount(){
        return AjaxResult.success(reportInformationService.selectCountByStatus(SecurityUtils.getLoginUser().getUser().getNickName()));
    }

    /**
     * 报告签字处理
     */
    @PostMapping("/signReportDeal")
    @ApiOperation(value="报告签字处理")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult signReportDeal(@RequestBody ReportInformation reportInformation)throws Exception {
        //签字处理
        int ret = reportInformationService.dealReport(reportInformation);
        return toAjax(ret);
    }


    /**
     * 修改报告状态
     */
    @PostMapping("/editState")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value="修改报告状态")
    public AjaxResult editState(@RequestBody ReportInformation reportInformation) throws Exception {
        return toAjax(reportInformationService.updateReportStateById(reportInformation.getId(), reportInformation.getState()));
    }

    /**
     * 报告归档
     */
    @GetMapping("/filing/{id}")
    @ApiOperation(value="报告归档")
    public AjaxResult filing(@PathVariable String id) throws Exception {
        ReportInformation reportInformation = new ReportInformation();
        reportInformation.setId(id);
        reportInformation.setState("6");
        reportInformation.setFilier(SecurityUtils.getLoginUser().getUser().getNickName());
        return AjaxResult.success(reportInformationService.updateReportInformation(reportInformation));
    }

    /**
     * 报告编号是否存在
     */
    @GetMapping("/isExits/{reportNum}")
    @ApiOperation(value="报告编号是否存在")
    public AjaxResult isExits(@PathVariable String reportNum) {
        int count = reportInformationService.selectReportNumExits(reportNum);
        return AjaxResult.success(count);
    }

    /**
     * 首页查询报告统计情况
     */
    @GetMapping("/getIndexReportStas")
    @ApiOperation(value="首页查询报告统计情况")
    public AjaxResult getIndexReportStas(){
        //根据月份获取总报告情况
        List<HashMap<String, String>> getAllReport = reportInformationService.selectCountByState(null);
        //获取已批准报告数量
        List<HashMap<String, String>> getApprReport = reportInformationService.selectCountByState("8");
        //获取已归档报告数量
        List<HashMap<String, String>> getFillReport = reportInformationService.selectCountByState("11");
        //数据拼接
        List<Map<String, List<String>>> reportList = new ArrayList<Map<String, List<String>>>();
        for(int i = 0; i < getApprReport.size(); i++){
            getAllReport.add(getApprReport.get(i));
        }
        for(int i = 0; i < getFillReport.size(); i++){
            getAllReport.add(getFillReport.get(i));
        }
        return new AjaxResult();
     }

    /**
     * 删除报告信息
     */
    @Log(title = "报告信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(reportInformationService.deleteReportInformationByIds(ids));
    }

    /**
     * 报告归档
     */
    @GetMapping("/bggd/{ids}")
    @ApiOperation(value="报告归档")
    public AjaxResult bggd(@PathVariable String[] ids)
    {
        String filier = SecurityUtils.getLoginUser().getUser().getNickName();
        String filiTime = DateUtils.getTime();
        return toAjax(reportInformationService.updateBatchGd(filier, filiTime, ids));
    }

    /**
     * 查询报告历史版本信息
     */
    @GetMapping(value = "/getReportHistory/{id}")
    @ApiOperation(value="查询报告历史版本信息")
    public AjaxResult selectReasonById(@PathVariable("id") String id){
        String reportHistory = reportInformationService.selectReportHistoryById(id);
        Map<String, String> reportHistoryMap = new HashMap<String, String>();
        reportHistoryMap.put("reportHistory", reportHistory);
        String chiefReg = StringUtils.split(reportHistory, '.')[0] + "(1)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length());
        if(new File(chiefReg).exists()){
            reportHistoryMap.put("chiefRegHistory", StringUtils.split(reportHistory, '.')[0] + "(1)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length()));
        }
        String examineReg = StringUtils.split(reportHistory, '.')[0] + "(2)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length());
        if(new File(examineReg).exists()){
            reportHistoryMap.put("examineRegHistory", StringUtils.split(reportHistory, '.')[0] + "(2)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length()));
        }
        String apprReg = StringUtils.split(reportHistory, '.')[0] + "(3)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length());
        if(new File(apprReg).exists()){
            reportHistoryMap.put("apprRegHistory", StringUtils.split(reportHistory, '.')[0] + "(3)" + StringUtils.substring(reportHistory, reportHistory.indexOf('.'), reportHistory.length()));
        }
        return AjaxResult.success(reportHistoryMap);
    }

    /**
     * 批量下载设备二维码信息
     */
    @GetMapping("/downReport")
    @ApiOperation(value="批量下载设备二维码信息")
    public void gengerateReportInfo(HttpServletResponse response, @RequestParam String userName, @RequestParam("ids") String[] ids) throws IOException {
        //根据设备id获取设备信息列表
        List<ReportInformation> reportList = reportInformationService.selectReportByIds(ids);
        if(reportList.size() == 1){
            ReportInformation reportInformation = reportList.get(0);
            //获取报告封面和内容
            List<DownloadFile> downloadFiles = new ArrayList<DownloadFile>();
            //设置返回数据格式
            response.setContentType("application/x-msdownload");
            // 设置Response容器的编码
            response.setCharacterEncoding("UTF-8");
            String fileName = reportInformation.getReportNum();
            String actualEndTime =DateUtils.getTime();
            fileName += actualEndTime + ".zip";
            response.setHeader("Content-Disposition","attachment; filename="+fileName);
            ZipUtil.toZip3(downloadFiles, response.getOutputStream());
            reportInformation.setDowner(userName);
            reportInformationService.updateReportInformation(reportInformation);
        }else if(reportList.size() > 1){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload");
            String fileName = "report";
            String actualEndTime =DateUtils.getTime();
            fileName += actualEndTime + ".zip";
            response.setHeader("Content-Disposition","attachment; filename="+fileName);
            List<DownloadFile> downloadFiles =new ArrayList<>();
            for(int i = 0; i < reportList.size(); i++){
                //内容文件
                DownloadFile contentFile = new DownloadFile();
                contentFile.setFileName(reportList.get(i).getReportNum() + ".pdf");
                InputStream isContent = new FileInputStream(new File(StringUtils.replace(reportList.get(i).getPdfReport(), "/profile", RuoYiConfig.getProfile())));
                contentFile.setInputStream(isContent);
                downloadFiles.add(contentFile);
            }
            ZipUtil.toZip3(downloadFiles, response.getOutputStream());
            //批量下载更新
            reportInformationService.updateBatchDown(userName, DateUtils.getTime(), ids);
        }
    }
}
